package com.jsg.sl651.entity.frame.body.report;

import com.jsg.sl651.constant.EncodingElementIdentifier;
import com.jsg.sl651.entity.data.Element;
import com.jsg.sl651.entity.data.Identifier;
import com.jsg.sl651.entity.frame.body.MessageBody;
import com.jsg.sl651.entity.station.RemoteTelemetryStationAddress;
import com.jsg.sl651.enums.ClassificationOfStations;
import com.jsg.sl651.enums.CodingElementEnum;
import com.jsg.sl651.enums.CommunicationMessageType;
import com.jsg.sl651.enums.FunctionCode;
import com.jsg.sl651.util.ByteUtil;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.time.LocalDateTime;

/**
 * 测试报
 */
@NoArgsConstructor
@Getter
@Setter
public class TestReport extends ReportMessageBody{

    // 测站分类码
    private ClassificationOfStations classificationOfStations;
    // 观测时间
    private LocalDateTime observationTime;

    @Override
    protected MessageBody decodeHex(byte[] bytes) throws Exception {
        return decodeCommon(bytes, CommunicationMessageType.HEX);
    }

    @Override
    protected MessageBody decodeAscii(byte[] bytes) throws Exception {
        return decodeCommon(bytes, CommunicationMessageType.ASCII);
    }


    private MessageBody decodeCommon(byte[] bytes, CommunicationMessageType messageType) throws Exception {
        // 转换成ByteBuf
        ByteBuf buffer = toBuf(bytes);
        // 根据消息类型读取固定报文长度
        int fixedLength = (messageType == CommunicationMessageType.HEX) ? 8 : 16;
        decodeBasic(ByteUtil.readBytes(buffer, fixedLength));
        // 测站地址
        Identifier identifier = (messageType == CommunicationMessageType.HEX) ? Identifier.createHex(buffer) : Identifier.createAscii(buffer);
        Element<RemoteTelemetryStationAddress> addressElement = EncodingElementIdentifier.parser(messageType, identifier);
        this.remoteTelemetryStationAddress = addressElement.getData();
        addElement(addressElement);
        // 有一个字节的测站分类码
        byte stations = buffer.readByte();
        this.classificationOfStations = ClassificationOfStations.getByCode(messageType, stations);
        // 解析其他元素
        parserElement(messageType, buffer);
        // 获取观测时间
        this.observationTime = (LocalDateTime) getElement(messageType, CodingElementEnum.FF0H).getData();
        return this;
    }

    @Override
    public int getFunctionCode() {
        return FunctionCode.TEST_MESSAGE.getCode();
    }
}
